using System;
using UnityEngine;
using UnityEngine.UI;

namespace UnityX
{
    /// <summary>
    /// 剪裁图片显示成圆形
    /// </summary>
    [DisallowMultipleComponent]
    [RequireComponent(typeof(CanvasRenderer))]
    [AddComponentMenu("UI/UnityX/Image Circle")]
    public class ImageCircle : MaskableGraphic
    {
        [SerializeField]
        protected Texture m_Texture;
        [Range(12, 360)]
        [SerializeField]
        protected int m_VertCount = 60;
        public override Texture mainTexture
        {
            get
            {
                if (m_Texture == null)
                {
                    if (material != null && material.mainTexture != null)
                    {
                        return material.mainTexture;
                    }
                    return s_WhiteTexture;
                }
                return m_Texture;
            }
        }
        public Texture texture
        {
            get
            {
                return m_Texture;
            }
            set
            {
                if (m_Texture == value)
                    return;
                m_Texture = value;
                SetVerticesDirty();
                SetMaterialDirty();
            }
        }
        public int vertCount { get => m_VertCount; set { m_VertCount = value; SetVerticesDirty(); } }

        protected ImageCircle()
        {
            useLegacyMeshGeneration = false;
        }
        protected override void OnPopulateMesh(VertexHelper vh)
        {
            vh.Clear();
            Rect rect = GetPixelAdjustedRect();
            Color32 color = this.color;
            float rx = rect.width / 2;
            float ry = rect.height / 2;
            float cx = rect.x + rx;
            float cy = rect.y + ry;
            double gap = Math.PI * 2 / m_VertCount;
            //中心点
            vh.AddVert(new Vector3(cx, cy), color, new Vector2(0.5f, 0.5f));
            //外围点
            for (int i = 0; i < m_VertCount; i++)
            {
                float x = (float)Math.Cos(i * gap);
                float y = (float)Math.Sin(i * gap);
                vh.AddVert(new Vector3(rx * x + cx, ry * y + cy), color, new Vector2((x + 1) / 2, (y + 1) / 2));
            }
            //面
            for (int i = 1; i < m_VertCount; i++)
            {
                vh.AddTriangle(0, i, i + 1);
            }
            vh.AddTriangle(0, m_VertCount, 1);
        }
    }
}